package main

import (
	"context"
	"log"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()
	resp, err := cli.Grant(context.TODO(), 10)
	if err != nil {
		log.Fatal(err)
	}
	_, err = cli.Put(context.TODO(), "age", "18", clientv3.WithLease(resp.ID))
	if err != nil {
		log.Fatal(err)
	}
	// ctx, _ := context.WithTimeout(context.TODO(), 5*time.Second)
	ch, err := cli.KeepAlive(context.TODO(), resp.ID)
	go func() {
		for range ch {
			// log.Println("自动续租", <-ch)
			ka := <-ch
			if ka != nil {
				log.Println(ka.TTL)
			} else {
				log.Println("不可能")
			}
		}
	}()
	if err != nil {
		log.Fatal(err)
	}
	for {
		getResp, err := cli.Get(context.TODO(), "age")
		if err != nil {
			log.Fatal(err)
		}
		if getResp.Count == 0 {
			log.Println("key过期了")
			break
		}
		log.Println(getResp.Kvs)
		time.Sleep(2 * time.Second)
	}
}
